// 购物车相关的数据存这里
export default {
  namespaced: true,

  // state: {
  //   cartItems: [], // 购物车中的商品数据
  // },

  state() {
    const defaultValue = uni.getStorageSync('cart')
      ? JSON.parse(uni.getStorageSync('cart'))
      : []

    const defaultAddress = uni.getStorageSync('address')
      ? JSON.parse(uni.getStorageSync('address'))
      : {}

    return {
      cartItems: defaultValue,
      address: defaultAddress,
    }
  },

  getters: {
    // 所有商品的总数
    total(state) {
      return state.cartItems.reduce((sum, item) => sum + item.goods_count, 0)
    },

    fullAddress(state) {
      const { provinceName, cityName, countyName, detailInfo } = state.address
      if (!provinceName) return ''
      return provinceName + cityName + countyName + detailInfo
    },

    // 统计购物车中已勾选商品的总数量
    checkedTotal(state) {
      let result = 0

      state.cartItems.forEach((item) => {
        if (item.goods_state) {
          result += item.goods_count
        }
      })

      return result
    },

    // 已勾选的商品的总价
    checkedAmount(state) {
      let result = 0

      state.cartItems.forEach((item) => {
        if (item.goods_state) {
          result += item.goods_count * item.goods_price
        }
      })

      return result.toFixed(2)
    },
  },

  mutations: {
    updateAllState(state, checked) {
      // 遍历商品，更新所有的 goods_state
      state.cartItems.forEach((x) => {
        x.goods_state = checked
      })

      // 持久化到本地存储
      uni.setStorageSync('cart', JSON.stringify(state.cartItems))
    },

    setAddress(state, address) {
      state.address = address

      uni.setStorageSync('address', JSON.stringify(state.address))
    },

    addToCart(state, obj) {
      // obj这个商品在购物车中是否存在 存在就++
      const res = state.cartItems.find((item) => item.goods_id === obj.goods_id)

      if (res) {
        res.goods_count++
      } else {
        state.cartItems.push(obj) // 不存在
      }

      // 将购物车信息保持到本地缓存中
      uni.setStorageSync('cart', JSON.stringify(state.cartItems))

      console.log('仓库中最新数据: ', state.cartItems)
    },

    changeState(state, id) {
      const res = state.cartItems.find((item) => item.goods_id === id)
      if (res) {
        res.goods_state = !res.goods_state

        uni.setStorageSync('cart', JSON.stringify(state.cartItems))
      }
    },

    removeGoods(state, item) {
      state.cartItems = state.cartItems.filter(
        (x) => x.goods_id !== item.goods_id
      )

      uni.setStorageSync('cart', JSON.stringify(state.cartItems))
    },

    // this.$store.commit('cart/changeCount', {id: 1, number: 9})
    changeCount(state, { id, number }) {
      const res = state.cartItems.find((item) => item.goods_id === id)

      if (res) {
        res.goods_count = number

        uni.setStorageSync('cart', JSON.stringify(state.cartItems))
      }
    },
  },

  actions: {},
}
